<!--  -->
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogStatus ? '新增用户' : '修改用户'"
    width="30%"
    @close="dialogClose"
    @open="dialogOpen"
  >
    <el-form
      ref="formRef"
      :rules="formRule"
      :model="form"
      label-width="100"
    >
      <el-form-item
        prop="type"
        label="权限"
      >
        <el-select
          v-model="form.type"
          placeholder=" "
          :disabled="true"
        >
          <el-option
            v-for="(value, key) in roleUserLevelEnum"
            :key="key"
            :label="key"
            :value="value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        prop="func"
        label="权限"
        placeholder=" "
      >
        <el-cascader
          v-model="form.func"
          :options="cascaderOptions"
          class="w-full"
          :props="{ multiple: true }"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('setDialogVisible', false)">取消</el-button>
        <el-button
          type="primary"
          @click="createFilm(formRef)"
        > 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { inject, ref } from "vue";
import { ElDialog, ElCascader } from "element-plus";
import { roleUserLevelEnum } from "@/enum";
import { formRule } from "../rule";
import type { FormInstance } from "element-plus";
import { fetchCreateUser, fetchUpdateRole } from "@/service";
import { routerToCascader } from '../utils';
import { formatJson } from "@/utils";
const emit = defineEmits([
  "getFilmsList",
  "setDialogStatus",
  "setDialogVisible"
]);
const props = defineProps<{ updateForm: FilmsApi.FilmsRequest }>();
const formRef = ref<FormInstance>();
const cascaderOptions = routerToCascader();
const dialogStatus = inject<any>("dialogStatus", false);
const dialogVisible = inject<any>("dialogVisible", false);
const form = ref<any>({
  func:'',
  type: undefined
});

async function createFilm(formEl: any): Promise<void> {
  let res = null;
  await formEl.validate(async (valid: any, fields:string) => {
    if (valid) {
      if (dialogStatus.value) res = await fetchCreateUser({...form.value, func: formatJson(form.value?.func)});
      else res = await fetchUpdateRole({...form.value, func: formatJson(form.value?.func)});
      if (res?.code === 0) {
        emit("setDialogVisible", false);
        window.$message({
          type: "success",
          message: dialogStatus.value ? "创建成功" : "修改成功"
        });
        emit("getFilmsList");
      }
    } else {
      console.log('error submit!', fields);
    }
  });
}

function dialogClose() {
  form.value = {
    type: "",
    releaseTime: new Date()
  };
}
function dialogOpen() {
  if (!dialogStatus.value) form.value = props?.updateForm;
}
</script>

<style lang="scss" scoped></style>
